package lesson03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 *  // 公平锁，新的线程进来后直接进队列等待，先到的先执行
 *  测试过程中加入睡眠时间会跟准确，for循环要放在外面, for循环此次大才明显，如果循环小则需睡眠体现
 */
public class ReentrantLoock5 extends Thread {


    ReentrantLock lock = new ReentrantLock(true); // 公平锁，新的线程进来后直接进队列等待，先到的先执行
    public void run() {
        for (int i = 0; i < 9; i++) {
            try {

                // for (int i = 0; i < 10; i++) {
                    lock.lock();
                    //TimeUnit.SECONDS.sleep(1);
                    System.out.println(Thread.currentThread().getName() + "-----" + i);
                // } 死循环
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
         }
    }

    public static void main(String[] args) {
        ReentrantLoock5 rl = new ReentrantLoock5();
        Thread t1 = new Thread(rl);
        Thread t2 = new Thread(rl, "t2");
        t1.start();
        t2.start();

    }
}
